'''
Automatically set the static IP address and hosts alias 

TODO(zedada264@foxmail.com Taiga-A) :
    Increase system identification and configure host aliases across platforms to facilitate remote connections

'''

import os

server_name_with_ip = {
    "master01" : "192.168.1.200",
    "node01" : "192.168.1.201",
    "node02" : "192.168.1.202",
    "node03" : "192.168.1.203",
    "node04" : "192.168.1.204",
    "node05" : "192.168.1.205",
    "node06" : "192.168.1.206",
    "node07" : "192.168.1.207",
    "node08" : "192.168.1.208",
    "node09" : "192.168.1.209"
}

conf = {
    "IPADDR" : "0.0.0.0",
    "BOOTPROTO" : "static",
    "NETMASK": "255.255.255.0",
    "GATEWAY": "192.168.1.1",
    "DNS1": "8.8.8.8"
}

file_path = {
    "ip_config": "/etc/sysconfig/network-scripts/ifcfg-enp3s0",
    "hosts": "/etc/hosts"
}

def ip_config():
    # ip config
    server_name = input("purse server name:")
    staticip = server_name_with_ip.get(server_name)
    if (not staticip):
        print("error can't find server name :", server_name)
        exit(-1)
    
    conf["IPADDR"] = staticip

    file = open(file_path["ip_config"], "r")
    

    base_data = file.readlines()
    change_data = ""

    for line_data in base_data:
        [k, v] = line_data.replace("\n", "").split("=")
        if (conf.get(k)):
            v = conf.get(k)
            conf[k] = ""
        change_data += k + "=" + v + "\n"
    
    for [k, v] in conf.items():
        if (not v):
            continue
        change_data += k + "=" + v + "\n"
    
    file.close()
    file = open(file_path["ip_config"], "w")
    file.write(change_data)
    file.close()
    os.system("ifup enp3s0")

def hosts_config():
    # hosts
    file = open(file_path["hosts"], "a")
    for [k, v] in server_name_with_ip.items():
        file.write("\n" + v + "   " + k)

def ssh_config():
    os.system("bash auto_ssh.sh")

if __name__ == "__main__":
    while (True):
        cmd = input("cmd: [exit] [ip] [hosts] [ssh] : ")
        print(cmd)
        if cmd == "ip":
            ip_config()
        elif cmd == "hosts":
            hosts_config()
        elif cmd == "ssh":
            ssh_config()
        elif cmd == "exit":
            print("Bye!")
            break
        else:   
            print("undefine command ", cmd)

    

    
